package com.mc.util;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class JsonHttpClient {

    private static final Logger log = LoggerFactory.getLogger(JsonHttpClient.class);


    public static void main(String[] args) throws IOException {
        /**
         * 如果需要手动给header中添加东西的时候，可以这样。
         */
        Map<String, String> header = new HashMap<>();
        header.put("_user", "oms");
        header.put("_token", "QWERTYUIOP");
        String url = "aaa";
        Object queryVo = "cccc";
        Object data = JsonHttpClient.postJsonWithHeader(url, JSON.toJSONString(queryVo), header);
    }

    public static String postJsonWithHeader(String url, String json, Map<String, String> header) throws ParseException, IOException {

        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            StringEntity stringEntity = new StringEntity(json, "UTF-8");
            stringEntity.setContentType("text/json");
            httpPost.setEntity(stringEntity);
            httpPost.addHeader("Content-type", "application/json;charset=UTF-8");
            /** 设置头信息 */
            if (header != null && header.size() > 0) {
                for (String key : header.keySet()) {
                    if (StringUtils.isNotBlank(key)) {
                        httpPost.addHeader(key, header.get(key));
                    }
                }
            }
            CloseableHttpClient httpclient = HttpClients.createDefault();
            response = httpclient.execute(httpPost);
            int code = response.getStatusLine().getStatusCode();
            if (code == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    try {
                        return EntityUtils.toString(entity);
                    } finally {
                        EntityUtils.consume(entity);
                    }
                }
            } else {
                log.info("server:{} response error, statusCode:{}", url, code);
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error("post error", e);
                }
            }
        }
        return null;
    }
}
